package com.ag.utils;

import java.io.IOException;
import java.lang.reflect.Type;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

public class StringConvertJSONObject2Serializer implements ObjectSerializer {

	@Override
	public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features)
			throws IOException {
		SerializeWriter out = serializer.out;
		
		String string = (String) object;
		
		JSONObject json = JSON.parseObject(string);
		if(json == null) {
			out.writeNull();
		} else {
			for(String key : json.keySet()) {
				Object v = json.get(key);
				if(v != null && v instanceof String) {
					String vStr = (String) v;
					if(StringUtils.startsWith(vStr, "{")) {
						json.put(key, JSON.parseObject(vStr));
					} else if(StringUtils.startsWith(vStr, "[")) {
						json.put(key, JSON.parseArray(vStr));
					}
				}
			}
			
			out.write(json.toJSONString());
		}
	}

}
